//
//  CheckNetwork.m
//
//  Created by EvanZ on 13-1-30.
//  Copyright (c) 2013年 EvanZ. All rights reserved.
//

#import "CheckNetwork.h"

@implementation CheckNetwork

+ (BOOL)isExistenceNetwork{
    BOOL isExistenceNetwork;
    
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    
    switch ([reachability currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = FALSE;
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = TRUE;
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = TRUE;
            break;
        default:
            isExistenceNetwork = FALSE;
            break;
    }
    
    if (!isExistenceNetwork) {
//        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"没用可用网络" message:@"请检查网络连接" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
//        [alertView show];
//        [alertView release];
    }
    return  isExistenceNetwork;
}


+ (BOOL) checkNetworkIsValid {
    
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    
    
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags) {
        return NO;
    }
    
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    // = flags & kSCNetworkReachabilityFlagsIsWWAN;
    BOOL nonWifi = flags & kSCNetworkReachabilityFlagsTransientConnection;
    BOOL moveNet = flags & kSCNetworkReachabilityFlagsIsWWAN;
    
    return ((isReachable && !needsConnection) || nonWifi || moveNet) ? YES : NO;
    
}

@end
